# -*- encoding: utf-8 -*-
'''
@文件    :logging_middle_ware.py
@说明    :针对日志文件生成，添加到中间件中
@时间    :2024/10/30 21:41:40
@作者    :冯佳辉
@版本    :
'''

import time, os
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import Request, HTTPException
import logging


class Logging_Middle_Ware(BaseHTTPMiddleware):
    print("生成日志开始---》")

    def __init__(self, app):
        super().__init__(app)
        log_format = "time:%(asctime)s - log_level:%(levelname)s - log_info:%(message)s"
        logging.basicConfig(
            level=logging.DEBUG,  #DEBUG<INFO<WARNING<ERROR<CRITICAL
            format=log_format,
            filename=self.create_log_folder,
            encoding='utf-8')

    @property
    def create_log_folder(self):
        log_folder_name = time.strftime("%Y_%m_%d", time.localtime())
        log_file = time.strftime("%Y_%m_%d_%H", time.localtime()) + '.log'
        log_file_folder_path = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'log',
            log_folder_name)
        if not os.path.exists(log_file_folder_path):
            os.mkdir(log_file_folder_path)
        return os.path.join(log_file_folder_path, log_file)

    async def dispatch(self, request: Request, call_next):
        start_time = time.time()
        response = await call_next(request)
        end_time = time.time()
        process_time = end_time - start_time
        log_message = (
            f"请求方法：{request.method} _ 请求路径：{request.url.path} _ 请求参数：{request.query_params} _ 响应状态：{response.status_code} _ 处理时间：{process_time}"
        )
        logging.debug(log_message)
        return response
